let arr = Array.from({ length: 50 }, _ => Math.random() * 1000 | 0);
console.log('原始数组:', arr);

// TODO 冒泡算法

function bubbleSort(arr = []) {
    let count = 0;
    let { length: len } = arr;
    for (let i = 0; i < len; i++) {
        for (j = 0; j < len - i - 1; j++) {
            count++
            if (arr[j] > arr[j + 1]) {
                // console.log(arr[i], arr[j + 1]);
                [arr[j + 1], arr[j]] = [arr[j], arr[j + 1]]
            }
        }
    }
    console.log(count);
    return arr;
};
// console.log(bubbleSort(arr));
// TODO 选择排序

function selectionSort(arr = []) {
    let { length: len } = arr;
    let minIndex;
    for (let i = 0; i < len; i++) {
        minIndex = i;
        for (let j = i + 1; j < len; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j
            }
        }
        [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]]
    }
    return arr;
}
// console.log(selectionSort(arr));

// TODO 插入排序


function insertionSort(arr = []) {
    let { length } = arr;
    let preIndex, current;
    for (let i = 1; i < length; i++) {
        preIndex = i - 1;
        current = arr[i];
        while (preIndex >= 0 && arr[preIndex] > current) {
            arr[preIndex + 1] = arr[preIndex];
            preIndex--
        }
        arr[preIndex + 1] = current
    }
    return arr
}
console.log(insertionSort(arr));